home *** CD-ROM | disk | FTP | other *** search
/ The Atari Compendium / The Atari Compendium (Toad Computers) (1994).iso / files / prgtools / gnustuff / minix / libsrc~1.z / libsrc~1 / getwd.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-12-28  |  1.8 KB  |  83 lines

  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. #include <sys/dir.h>
  5.  
  6. /* getwd shamelessly adapted from:              ++jrb               */
  7. /* pwd - print working directory        Author: Adri Koppes */
  8.  
  9. /* char *getwd(path)
  10.  * char *path;
  11.  * fill CWD in path, returns path
  12.  * on error return NULL with error string in path
  13.  */
  14.  
  15. char *getwd(path)
  16. char *path;
  17. {
  18.     register int fd;
  19.     register char *n;
  20.     char name[128];
  21. #ifdef __STDC__
  22.     char *rindex(_CONST char *, int);
  23. #else
  24.     extern char *rindex();
  25. #endif
  26.     struct stat s, st;
  27.     struct direct d;
  28.  
  29.     *name = 0;
  30.     stat(".", &s);
  31.     do {
  32.         if ((fd = open("..",0)) < 0) {
  33.             strcpy(path, "Can't open ..");
  34.             return (char *)NULL;
  35.         }
  36.         st.st_dev = s.st_dev;
  37.         st.st_ino = s.st_ino;
  38.         st.st_mode = s.st_mode;
  39.         st.st_nlink = s.st_nlink;
  40.         st.st_uid = s.st_uid;
  41.         st.st_gid = s.st_gid;
  42.         st.st_rdev = s.st_rdev;
  43.         st.st_size = s.st_size;
  44.         st.st_atime = s.st_atime;
  45.         st.st_mtime = s.st_mtime;
  46.         st.st_ctime = s.st_ctime;
  47.         stat("..", &s);
  48.         chdir("..");
  49.         if (s.st_dev == st.st_dev)
  50.             do
  51.                 if (read(fd, (char *)&d, (int)sizeof(struct direct)) < (int)sizeof(struct direct)) {
  52.                     strcpy(path,"Can't read ..");
  53.                     return (char *)NULL;
  54.                 }
  55.             while(d.d_ino != st.st_ino);
  56.         else
  57.             do {
  58.                 if (read(fd, (char *)&d, (int)sizeof(struct direct)) < (int)sizeof(struct direct)) {
  59.                     strcpy(path, "Can't read ..");
  60.                     return (char *)NULL;
  61.                 }
  62.                 stat(d.d_name, &s);
  63.             } while ((s.st_dev != st.st_dev) || (s.st_ino != st.st_ino));
  64.         close(fd);
  65.         if (strcmp(".",d.d_name)) {
  66.             strcat(name,"/");
  67.             strcat(name,d.d_name);
  68.         }
  69.     } while ((s.st_ino != st.st_ino) || (s.st_dev != st.st_dev));
  70.     if (!*name)
  71.     {
  72.         strcpy(path, "/");
  73.         return path;
  74.     }
  75.     *path = '\0';
  76.     while (n = rindex(name, '/')) {
  77.         strcat(path,n);
  78.         *n = 0;
  79.     }
  80.     strcat(path, name);
  81.     return path;
  82. }
  83.